package jp.dodododo.aop.interceptors;

import jp.dodododo.aop.HasTargetClass;

import org.aopalliance.intercept.ConstructorInvocation;
import org.aopalliance.intercept.Interceptor;
import org.aopalliance.intercept.Invocation;
import org.aopalliance.intercept.MethodInvocation;

public abstract class AbstractInterceptor implements Interceptor {
	protected Class<?> getTargetClass(MethodInvocation invocation) {
		Class<?> ret = null;
		if (invocation instanceof HasTargetClass) {
			ret = ((HasTargetClass) invocation).getTargetClass();
		}
		if (ret == null) {
			ret = invocation.getMethod().getDeclaringClass();
		}
		return ret;
	}

	protected Class<?> getTargetClass(Invocation invocation) {
		if (invocation instanceof HasTargetClass) {
			return ((HasTargetClass) invocation).getTargetClass();
		}
		if (invocation instanceof MethodInvocation) {
			return getTargetClass((MethodInvocation) invocation);
		} else if (invocation instanceof ConstructorInvocation) {
			return getTargetClass((ConstructorInvocation) invocation);
		} else {
			throw new IllegalArgumentException("Unknown type. [" + invocation.getClass() + "]");
		}
	}

	protected Class<?> getTargetClass(ConstructorInvocation invocation) {
		Class<?> ret = null;
		if (invocation instanceof HasTargetClass) {
			ret = ((HasTargetClass) invocation).getTargetClass();
		}
		if (ret == null) {
			ret = invocation.getConstructor().getDeclaringClass();
		}
		return ret;
	}
}
